package websocketgulu.demo.Utils;



import websocketgulu.demo.pojo.WaveHeader;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author: 苏成
 * @Date: 2021/10/05/16:54
 * @Description: 将数据写入Wav文件
 */
public class DataToWav {


    /**
     * 创建一个Wav文件并写入头部
     * @param target
     * @throws IOException
     */
    public static FileOutputStream writeWavHeader(String target) throws IOException {
//        FileInputStream fis = new FileInputStream(src);
        FileOutputStream fos = new FileOutputStream(target);

        int DataSize = 1024;

        //填入参数，比特率等等。这里用的是16位单声道 8000 hz
        WaveHeader header = new WaveHeader();
        //长度字段 = 内容的大小（PCMSize) + 头部字段的大小(不包括前面4字节的标识符RIFF以及fileLength本身的4字节)
        header.fileLength = DataSize + 36;
        header.FmtHdrLeth = 16;
        header.BitsPerSample = 16;
        header.Channels = 1;
        header.FormatTag = 0x0001;
        header.SamplesPerSec = 8000;
        header.BlockAlign = (short) (header.Channels * header.BitsPerSample / 8);
        header.AvgBytesPerSec = header.BlockAlign * header.SamplesPerSec;

        // 长度设置成1分钟
        // 硬件那边是每秒钟16帧，每帧的数据长度是1k，所以数据长度16 * 1024
        // 字段修改
//        header.DataHdrLeth = 16384 * 60;
        header.DataHdrLeth = 16384 * 10;

        byte[] h = header.getHeader();

        assert h.length == 44; //WAV标准，头部应该是44字节
        // write header
        fos.write(h, 0, h.length);

//        fos.close();
        System.out.println("Write Header OK!");
        return fos;
    }


    /**
     * 写入数据到wav文件之中
     * @param target
     * @param data
     * @throws IOException
     */
    public static void WriteWaveData(String target, byte[] data, FileOutputStream fos) throws IOException {
//        FileOutputStream fos= new FileOutputStream(target);
        fos.write(data);
        System.out.println("Write 1kb data !");
//        fos.close();
    }

}
